package online.westonline.com.westonline.ui;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.easy.west.westclient.Constants;
import com.easy.west.westclient.api.base.bean.SuccessBean;
import com.easy.west.westclient.api.meeting.bean.MeetRoomBean;
import com.easy.west.westclient.api.meeting.event.OrederCompleteEvnet;
import com.easy.west.westclient.api.message.event.CreateMessageEvent;
import com.easy.west.westclient.api.push.event.PushEvent;
import com.google.gson.Gson;
import com.hhl.library.FlowTagLayout;
import com.hhl.library.OnTagSelectListener;

import net.wujingchao.android.view.SimpleTagImageView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import online.westonline.com.westonline.MyApplication;
import online.westonline.com.westonline.R;
import online.westonline.com.westonline.adapter.tag.TagAdapter;
import online.westonline.com.westonline.base.BaseActivity;
import online.westonline.com.westonline.entry.MeetFormBean;
import online.westonline.com.westonline.entry.PushDataBean;
import online.westonline.com.westonline.entry.Tag;
import online.westonline.com.westonline.event.MeetingFormCompeleteEvent;
import online.westonline.com.westonline.utils.CacheUtils;
import online.westonline.com.westonline.utils.ToastUtils;
import online.westonline.com.westonline.utils.UiUtlis;

public class OrederMeetActivity extends BaseActivity {


    @BindView(R.id.tv_topbar_title)
    TextView tvTopbarTitle;
    @BindView(R.id.tv_topbar_title_center)
    TextView tvTopbarTitleCenter;
    @BindView(R.id.img_toolbar_menu)
    ImageView imgToolbarMenu;
    @BindView(R.id.tv_topbar_menu)
    TextView tvTopbarMenu;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.img_order_meetimg)
    SimpleTagImageView imgOrderMeetimg;
    @BindView(R.id.ra_meeting_message_info)
    RelativeLayout raMeetingMessageInfo;
    @BindView(R.id.tag_equa_layout)
    FlowTagLayout tagEquaLayout;
    @BindView(R.id.edit_beizhu)
    EditText editBeizhu;
    @BindView(R.id.check_push)
    CheckBox checkPush;
    @BindView(R.id.btn_push)
    Button btnPush;
    @BindView(R.id.tv_order_meet_name)
    TextView tvOrderMeetName;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.tv_order_type)
    TextView tvOrderType;
    @BindView(R.id.tv_order_state)
    TextView tvOrderState;
    @BindView(R.id.edit_meeting_flag)
    EditText editMeetingFlag;
    @BindView(R.id.edit_sitdown)
    EditText editSitdown;
    @BindView(R.id.tv_message_info_state)
    TextView tvMessageInfoState;
    @BindView(R.id.check_gaide_meeting)
    CheckBox checkGaideMeeting;
    private MeetRoomBean roomBean;
    private MeetFormBean meetFormBean_gaide;
    private int select_time;
    private TagAdapter<Tag> tagAdapter;
    private List<Tag> tagList = new ArrayList<>();
    private StringBuilder equia = new StringBuilder();
    private List<Tag> select_list = new ArrayList<>();
    private MeetFormBean meetFormBean;
    private StringBuilder select_con;
    public static int RESULT_QODE = 155;
    private String select_date;

    @Override
    protected void initview() {
        toolbar.setTitle("申请会议室");
        toolbar.setTitleTextColor(UiUtlis.getColor(R.color.colorMenuBtn));
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        //初始化会议室
        initroom();
        //初始化tag布局
        inittag();
        //初始化事件
        initsession();
    }

    private void initsession() {
        //多选事件
        tagEquaLayout.setOnTagSelectListener(new OnTagSelectListener() {
            @Override
            public void onItemSelect(FlowTagLayout parent, List<Integer> selectedList) {
                Log.e("选中的数量", selectedList.size() + "个");
                select_list = new ArrayList<>();
                if (selectedList.size() > 0) {
                    for (int pos : selectedList) {
                        //添加选中list
                        select_list.add(tagList.get(pos));
                        Log.e("提示", "入集合");
                    }
                }
            }
        });
        //填写基本信息
        raMeetingMessageInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putInt("time", select_time);
                bundle.putInt("mid", roomBean.getMrid());
                startActivityWithBundle(MeetFormActivity.class, false, bundle
                );
            }
        });
        //提交
        btnPush.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (meetFormBean == null&&meetFormBean_gaide==null) {
                    Snackbar.make(v, "请您填完基本信息", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                select_con = new StringBuilder();
                String result;
                //拆分集合
                if (select_list.size() > 0) {
                    for (Tag tag : select_list) {
                        select_con.append(tag.getId() + ",");
                    }
                    result = select_con.substring(0, select_con.length() - 1);
                } else {

                    result = select_con.append("").toString();
                }
                if (!TextUtils.isEmpty(editSitdown.getText().toString())) {
                    result = result + "," + 7;
                }
                if (!TextUtils.isEmpty(editMeetingFlag.getText().toString())) {
                    result = result + "," + 3;
                }
                if (checkGaideMeeting.isChecked())
                {
                    if (meetFormBean_gaide!=null)
                    {
                        //预约
                        MyApplication.getClient().orderMeeting(roomBean.getMrid()
                                , meetFormBean_gaide.getTitle(), select_date, select_time, CacheUtils.getInstance().getUser().getData().getId()
                                , meetFormBean_gaide.getDid(),meetFormBean_gaide.getNumber(),meetFormBean_gaide.getLeader(), meetFormBean_gaide.getStarttime()
                                , editSitdown.getText().toString(), editMeetingFlag.getText().toString(),meetFormBean_gaide.isPravite()
                                , meetFormBean_gaide.getPraviteReason(), result
                                , meetFormBean_gaide.getConstacts_phone(), meetFormBean_gaide.getConstacts_name());
                        showProgessDialog("请稍后");
                    }
                }
                else
                {
                    if (meetFormBean!=null)
                    {
                        //预约
                        MyApplication.getClient().orderMeeting(roomBean.getMrid()
                                , meetFormBean.getTitle(), select_date, select_time, CacheUtils.getInstance().getUser().getData().getId()
                                , meetFormBean.getDid(), meetFormBean.getNumber(), meetFormBean.getLeader(), meetFormBean.getStarttime()
                                , editSitdown.getText().toString(), editMeetingFlag.getText().toString(), meetFormBean.isPravite()
                                , meetFormBean.getPraviteReason(), result
                                , meetFormBean.getConstacts_phone(), meetFormBean.getConstacts_name());
                        showProgessDialog("请稍后");
                    }

                }

            }
        });
        //模板选中
        checkGaideMeeting.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked)
                {
                    meetFormBean_gaide = CacheUtils.getInstance().getMeetFormBeanGaide(MeetingGaideActivity.class.getSimpleName());
                    if (meetFormBean_gaide==null)
                    {
                        checkGaideMeeting.setChecked(false);
                        showNormalDialog(true, "提示", "模板内容为空是否前往编辑", "取消"
                               , new DialogInterface.OnClickListener() {
                                   @Override
                                   public void onClick(DialogInterface dialog, int which) {
                                       Bundle bundle = new Bundle();
                                       bundle.putInt("time", select_time);
                                       bundle.putInt("mid", roomBean.getMrid());
                                       startActivityWithBundle(MeetingGaideActivity.class,false,bundle);
                                   }
                               });
                    }
                    else
                    {
                        if (select_time==meetFormBean_gaide.getTimeType())
                        {
                            if (meetFormBean!=null)
                            {
                                showNormalDialog(true, "提示", "选中模板后您之前编辑的内容将会作废,是否继续?"
                                        , "取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                //请空原有实体
                                                meetFormBean = null;
                                            }
                                        });
                            }
                            CacheUtils.getInstance().saveMeetFormBean(roomBean.getMrid(),meetFormBean_gaide);
                            tvMessageInfoState.setText("(已使用模板)");
                        }
                        else
                        {
                            showNormalDialog(true, "提示", "模板时间中的会议开始时间不在当前时间段,是否前往更改"
                                    , "不更改", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Bundle bundle = new Bundle();
                                            //这里传不传时间类型都无所谓了,为了避免空指针先传着
                                            bundle.putInt("time",select_time);
                                            bundle.putInt("mid",roomBean.getMrid());
                                            startActivityWithBundle(MeetingGaideActivity.class,false,bundle);
                                        }
                                    });
                            checkGaideMeeting.setChecked(false);
                        }
                    }
                }
                else
                {
                        //清空模板实体
                        meetFormBean_gaide = null;
                        tvMessageInfoState.setText(" ");
                }
            }
        });
    }

    //初始化tag布局
    //1,投影仪 2,麦克风 3,会标 4,电视 5,无线话筒 6,音响 7,座牌 8,告示牌 9,茶水 10,矿泉水
    private void inittag() {
        tagList.add(new Tag(1, "投影仪"));
        tagList.add(new Tag(2, "麦克风"));
        //tagList.add(new Tag(3, "会标"));
        tagList.add(new Tag(4, "电视"));
        tagList.add(new Tag(6, "音响"));
        tagList.add(new Tag(5, "无线话筒"));
        //tagList.add(new Tag(7, "座牌"));
        tagList.add(new Tag(8, "告示牌"));
        tagList.add(new Tag(9, "茶水"));
        tagList.add(new Tag(10, "矿泉水"));
        tagAdapter = new TagAdapter<>(this);
        tagAdapter.onlyAddAll(tagList);
        tagEquaLayout.setAdapter(tagAdapter);
        tagAdapter.notifyDataSetChanged();
        //多选开启
        tagEquaLayout.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_MULTI);
    }

    private void initroom() {
        if (!TextUtils.isEmpty(roomBean.getImg())) {
            Glide.with(this).load(roomBean.getImg()).into(imgOrderMeetimg);
        } else {
            imgOrderMeetimg.setBackgroundResource(R.mipmap.icon);
        }
        //是否是vip
        if (roomBean.isVip()) {
            imgOrderMeetimg.setTagEnable(true);
        } else {
            imgOrderMeetimg.setTagEnable(false);
        }
        //详细内容设置
        tvOrderMeetName.setText(roomBean.getName());
        if (select_time == 0) {
            tvOrderTime.setVisibility(View.GONE);
        }
        if (select_time == 1) {
            tvOrderTime.setText("上午(8:30-12:00)可预约");
        }
        if (select_time == 2) {
            tvOrderTime.setText("下午(14:00-18:00)可预约");
        }
        if (select_time == 3) {
            tvOrderTime.setText("晚上(18:30-22:00)可预约");
        }
        if (select_time == 4) {
            tvOrderTime.setText("全天可预约");
        }
        //设置类型
        if (roomBean.getSize() == 1) {
            tvOrderType.setText("大型");
        }
        if (roomBean.getSize() == 2) {
            tvOrderType.setText("中型及以下");
        }
        //展示预约
        tvOrderState.setVisibility(View.GONE);

    }

    @Override
    protected void initdata() {
        roomBean = (MeetRoomBean) getIntent().getExtras().getSerializable("data");
        select_time = getIntent().getExtras().getInt("time");
        select_date = getIntent().getExtras().getString("date");
        //请空存储的表单
        CacheUtils.getInstance().clearForm(roomBean.getMrid());
    }

    @Override
    protected int setlayout() {
        return R.layout.activity_oreder_meet;
    }

    /***
     * 预定成功
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void orderSuccess(OrederCompleteEvnet eva) throws UnsupportedEncodingException {
        if (eva.isOk()) {
            SuccessBean successBean = eva.getBean();
            if (successBean.getStatus() == 1) {
                PushDataBean dataBean = new PushDataBean();
                dataBean.setType(Constants.NOTIFIY_TYPE_MEETING);
                dataBean.setMeeting(successBean.getData().toString());
                //创建消息（推送给管理员的）(查询时传0当然查询不是这个接口)
                MyApplication.getClient().createMessage("申请会议室"
                        + roomBean.getName(),successBean.getData().toString(),Constants.NOTIFIY_TYPE_MEETING
                ,CacheUtils.getInstance().getUser().getData().getId(),0);
                //推送
                MyApplication.getClient()
                        .push("会议室申请"
                                , CacheUtils.getInstance().getUser().getData().getName() + "申请会议室"
                                        + roomBean.getName()
                                , "略略略"
                                , Constants.NOTIFIY_TYPE_MEETING, successBean.getData().toString(), Constants.ACCESS_TOKEN1, Constants.ACCESS_TOKEN2
                                , Constants.ACCESS_TOKEN3);

            } else {
                Snackbar.make(tagEquaLayout, "抱歉,已被预约", Snackbar.LENGTH_SHORT).show();
            }
            dissmissDialog();
        }
        else
        {
            //ToastUtils.showToast(eva.getCodeDescribe());
            dissmissDialog();
        }
    }

    /**
     * 推送状态
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void pushstate(PushEvent eva) {
        if (eva.isOk()) {
            SuccessBean successBean = eva.getBean();
            if (successBean.getStatus() == 1) {

            } else {
                ToastUtils.showToast("推送失败");
                dissmissDialog();
            }
            dissmissDialog();
        } else {
            //ToastUtils.showToast(eva.getCodeDescribe());
            dissmissDialog();
        }
    }

    /**
     * 获取formBean
     *
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getFormBean(MeetingFormCompeleteEvent eva) {
        meetFormBean = eva.getMeetFormBean();
        Log.e("信息", "回来了");
        CacheUtils.getInstance().saveMeetFormBean(roomBean.getMrid(),eva.getMeetFormBean());
        tvMessageInfoState.setText("(基本信息已填写)");
    }

    /**
     * 创建消息
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void createMessage(CreateMessageEvent eva)
    {
        if (eva.isOk())
        {
            SuccessBean successBean = eva.getBean();
            if (successBean.getStatus()==1)
            {
                //成功
                Snackbar.make(tagEquaLayout, "预约成功", Snackbar.LENGTH_SHORT).show();
            }
            else
            {
                //失败
                Snackbar.make(tagEquaLayout, "失败:" + successBean.getData().toString(), Snackbar.LENGTH_SHORT).show();
            }
        }
    }

}
